require('js/lib/require_patch').monkeypatch(this); // android needs this. Apparently there are different contexts

var ui = require('js/ui/common/ui');

/*
 * Our custom treatment view component takes an initial
 * parameters that make up a previous treatment, and will be stored 
 * in an external database 
 * 
 */
exports.TreatmentWin = function(params) {
	Ti.API.debug('+-+-+-+  TreatmentWin params: ' + JSON.stringify(params));
	
	//create and populate the treatment object
	var mainView = ui.view({
		backgroundColor: '#000'
	});
	
	var SettingsView = require('js/ui/SettingsView');
	var UtilityWindow = require('js/ui/UtilityWindow');
	
	var instance = new UtilityWindow('Treatment', mainView, new SettingsView());

	// Problem Description
	var infoLabel = ui.label(params.text, {textAlign: 'center', width: '90%', height: '90%', top:10});
	var infoView = ui.view({backgroundColor: params.backgroundColor, 
		width: '100%', height: '800',
		borderColor: params.backgroundColor, borderWidth:10, borderRadius:5});
	var scrollView = Titanium.UI.createScrollView({
	    width:'75%',
	    height:'35%',
	    top:30,
	    showVerticalScrollIndicator:true,
	    showHorizontalScrollIndicator:true
	});
	scrollView.add(infoView);
	infoView.add(infoLabel);
	mainView.add(scrollView);
	
	// Add Therapy Selection
	var therapy = ui.button({title:'Select Therapy', top: '55%', height:30*globals.deviceFactor}, function(e){
		var therapies = globals.db.listPicklistItems('type = ?',['Therapy'])
		var therapySelect = Titanium.UI.createPicker({selectionIndicator: true, top:80, height:'35%'});
		therapies.unshift({name:'None', id:-1});
		for (var i=0, l=therapies.length; i<l; i++) {
			therapies[i].title = therapies[i].name;
		}
		therapySelect.add(therapies);
		therapySelect.addEventListener('change',function(e){
			if (e.row.id > -1) {
				therapy.title = 'Therapy: '+e.row.title;
				therapy.selectedId = e.row.id;
			}
			mainView.remove(therapySelect);
		});
		mainView.add(therapySelect);
	});
	mainView.add(therapy);
	
	// Add Exercise Selection
	var exercise = ui.button({title:'Select Exercise', top: '65%', height:30*globals.deviceFactor}, function(e){
		var exercises = globals.db.listPicklistItems('type = ?',['Exercise'])
		var exerciseSelect = Titanium.UI.createPicker({selectionIndicator: true, top:80, height:'35%'});
		exercises.unshift({name:'None', id:0});
		for (var i=0, l=exercises.length; i<l; i++) {
			exercises[i].title = exercises[i].name;
		}
		exerciseSelect.add(exercises);
		exerciseSelect.addEventListener('change',function(e){
			if (e.row.id > 0) {
				exercise.title = 'Exercise: '+e.row.title;
				exercise.selectedId = e.row.id;
			}
			mainView.remove(exerciseSelect);
		});
		mainView.add(exerciseSelect);
	});
	mainView.add(exercise);
	
	// Control Bar
	var controlLabels = {back: 'Done'};
	var controlFunctions = {back: function() { 
			saveResults();
			var win = params.winTrail.pop();
			while(win) {
				win.close();
				win = params.winTrail.pop();
			}
			
			instance.close();
		}};
	if (params.nextTest) {
		controlLabels.next = 'More';
		controlFunctions.next = function() { 
			saveResults();
			var TestView = require('js/ui/TestView');
			var tv = new TestView(params.nextTest);
			var win = new UtilityWindow('Breakout Test', tv, new SettingsView(), {backgroundImage: 'images/grain.png'});
			tv.addManagedWin(win);
			win.open();
			
			instance.close();
			
			tv.addEventListener('dismiss.test', function(e){
				win.close();
			});
		}
	}
	var controlView = ui.controlBar(controlLabels,controlFunctions,{bottom: 0});

	mainView.add(controlView);

	return instance;
	
	function saveResults(id) {
		var PatientTreatment = require('js/model/PatientTreatment');
		var treatment = new PatientTreatment({
			patient_id: globals.patient.id,
			provider_id: globals.provider.id,
			appointment_id: globals.appointment.id,
			treatment_id: params.id,
			notes: null
		});
		
		// Generate Patient Note
		var category = globals.db.listNoteCategories('name = ?',['Objective'])[0].id;
		var notes = globals.db.listPatientNotes(globals.patient.id, 'appointment_id = ?', [globals.appointment.id]);
		var PatientNote = require('js/model/PatientNote');
		var note = new PatientNote({
			patient_id : globals.patient.id,
			provider_id : globals.provider.id,
			appointment_id : globals.appointment.id,
			note_type : category,
			text: ''
		});
		var insertNote = true;
		for (var i=0, l=notes.length; i<l; i++) {
			if (notes[i].type === category) {
				note = notes[i];
				insertNote = false;
				note.text += '\n\n';
				break;
			}
		}
		// Append test results
		note.text = (note.text||'') + 'Functional Eval: ';
		var tests = globals.results;
		for (var i=0, l=tests.length; i<l; i++) {
			note.text += i > 0 ? ', ' + tests[i].test.name + ' ' : tests[i].test.name + ' ';
			switch (tests[i].result) {
				case 'fn':
					note.text += 'Functional Nonpainful';
					break;
				case 'fp':
					note.text += 'Functional Painful';
					break;
				case 'dn':
					note.text += 'Dysfunctional Nonpainful';
					break;
				case 'dp':
					note.text += 'Dysunctional Painful';
					break;
			}
		}
		globals.results = [];
		
		note.text += '\nTreatment: ';
		
		if (therapy.selectedId) {
			treatment.treatmentSelectionId = therapy.selectedId;
			globals.db.addPatientTreatment(treatment);
			note.text += therapy.title;
		}
		
		if (exercise.selectedId) {
			treatment.treatmentSelectionId = exercise.selectedId;
			globals.db.addPatientTreatment(treatment);
			note.text += exercise.title;
		}
		
		if (insertNote) {
			globals.db.addPatientNote(note);
		}
		else {
			globals.db.updatePatientNote(note);
		}
	}
}
